package com.instalinks.android.smspostservice.receiver;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import com.instalinks.android.lib.AppHelper;
import com.instalinks.android.smspostservice.utils.AppConfig;
import com.instalinks.android.smspostservice.utils.AppNotifications;
import com.instalinks.android.smspostservice.utils.Constants;
import com.instalinks.android.smspostservice.utils.enums.AppActivities;

public class SmsC2dmReceiver extends BroadcastReceiver {

	private AppConfig mAppCfg;
	private AppNotifications appNotifications;
	private Context mContext;

	@Override
	public void onReceive(Context context, Intent intent) {
		mAppCfg = new AppConfig(context);
		appNotifications = new AppNotifications(context);
		mContext = context;

		if (intent.getAction().equals(
				"com.google.android.c2dm.intent.REGISTRATION")) {
			handleRegistration(context, intent);
		} else if (intent.getAction().equals(
				"com.google.android.c2dm.intent.RECEIVE")) {
			handleMessage(context, intent);
		}
	}

	private void handleRegistration(Context context, Intent intent) {
		String registration = intent.getStringExtra("registration_id");

		if (intent.getStringExtra("error") != null) {
			// Registration failed, should try again later.
			Log.d("c2dm", "registration failed");
			String error = intent.getStringExtra("error");
			if (error == "SERVICE_NOT_AVAILABLE") {
				Log.d("c2dm", "SERVICE_NOT_AVAILABLE");
			} else if (error == "ACCOUNT_MISSING") {
				Log.d("c2dm", "ACCOUNT_MISSING");
			} else if (error == "AUTHENTICATION_FAILED") {
				Log.d("c2dm", "AUTHENTICATION_FAILED");
			} else if (error == "TOO_MANY_REGISTRATIONS") {
				Log.d("c2dm", "TOO_MANY_REGISTRATIONS");
			} else if (error == "INVALID_SENDER") {
				Log.d("c2dm", "INVALID_SENDER");
			} else if (error == "PHONE_REGISTRATION_ERROR") {
				Log.d("c2dm", "PHONE_REGISTRATION_ERROR");
			}
			appNotifications
					.notifyGenericMessage("Reg/UnReg for Notifications Failed : "
							+ error);
		} else if (intent.getStringExtra("unregistered") != null) {
			Log.d("c2dm", "unregistered");
			appNotifications
					.notifyGenericMessage("Device UnRegistered for Notifications");
			mAppCfg.sendRegistrationIdToHost("UNREG");
		} else if (registration != null) {
			Log.d("c2dm", registration);

			appNotifications
					.notifyGenericMessage("Device Registered for Notifications");
			mAppCfg.sendRegistrationIdToHost(registration);
		}
	}

	private void handleMessage(Context context, Intent intent) {

		mAppCfg.wakeUp(6000);
		String mode = intent.getExtras().getString("mode").toLowerCase();
		String field1 = intent.getExtras().getString("field1");
		String field2 = intent.getExtras().getString("field2");
		String field3 = intent.getExtras().getString("field3");

		if(field2 == null)
			field2 = "";
		if (field3 == null)
			field3 = "";

		field3 = field3.toLowerCase();

		// appNotifications.notifyClearAll();

		if (mode.equals("flash")){
			processFlash(field1,field2, true);
		}else if ( mode.equals("system") && field3.equals("flash")) { // FLASH
			processFlash(field1, field2, false);
		} else if (mode.equals("updateconfig")
				|| (mode.equals("system") && field3.equals("updateconfig"))) { // UPDATE
																				// CONFIG
			processUpdateConfig();
		} else if (mode.equals("system") && field3.equals("sms")) { // SYSTEM
																	// SMS
			field3 = field3.toLowerCase();
			processSms(field1, field2, false);
		} else if (mode.equals("sms") && mAppCfg.isWebSmsFlag()) { // WEB SMS
			processSms(field1, field2, true);
		}
	}

	private void processFlash(String message, String sender, boolean showInMessageBox) {

		if (showInMessageBox){
			addToMessagesToInbox( (sender.trim().length() == 0)? "TS-SUPPORT": sender, message);
			appNotifications.notifyGenericMessageExternal("Click to open messages", true, AppActivities.MessageInbox);
		}else {
			try {
				mAppCfg.pushNotificationToQueue(message);
			} catch (Exception e) {
				Log.e("[INSTALINKS]", e.getMessage());
			}

			appNotifications.notifyGenericMessage(message,
					AppActivities.Notification);
		}
		
	}

	private void processUpdateConfig() {
		try {
			mAppCfg.pushNotificationToQueue("Config Update Request");
		} catch (Exception e) {
			Log.e("[INSTALINKS]", e.getMessage());
		}

		appNotifications.notifyGenericMessage("Config Update",
				AppActivities.Notification);
		if (mAppCfg.updateConfigFromHost()) {
			appNotifications.notifyGenericMessage("Configuration Updated");
		}
	}

	private void processSms(String message, String sendTo, boolean showInMessageBox) {

		if (showInMessageBox)
			appNotifications.notifyGenericMessage("Web SMS Request Received");

		String[] phoneNums = sendTo.split(",");

		for (int i = 0; i < phoneNums.length; i++) {

			try {
				AppHelper.sendSms(mContext, phoneNums[i].trim(), message);

				if (showInMessageBox)
					addToMessagesToSentItems(phoneNums[i].trim(), message);
			} catch (Exception e) {
			}
		}
	}

	private void addToMessagesToInbox(String smsSender, String smsContent) {
		addToMessagesBox(Constants.URI_SMS_INBOX, smsSender, smsContent);
	}

	private void addToMessagesToSentItems(String smsSender, String smsContent) {
		addToMessagesBox(Constants.URI_SMS_SENTITEMS, smsSender, smsContent);
	}

	private void addToMessagesBox(String folderUri, String smsSender,
			String smsContent) {
		try {
			Uri uri = Uri.parse(folderUri);
			ContentResolver cr = mContext.getContentResolver();

			ContentValues cv = new ContentValues();
			cv.put("address", smsSender);
			cv.put("body", smsContent);
			cv.put("service_center","thinserver");
			if (folderUri.equals(Constants.URI_SMS_INBOX)){
				cv.put("read", 0);
				cv.put("type", Constants.SMS_INBOX);
			}

			cr.insert(uri, cv);
		} catch (Exception e) {
			mAppCfg.alert(e.getMessage());
		}
	}
}
